<template>
	<view class="clock-in">
		<uni-nav-bar dark :fixed="true" :border="false" background-color="#FFFFFF" status-bar title="打卡"
			left-icon="left" @clickLeft="toBack" color="#000" />
		<u-sticky offset-top="64">
			<u-subsection :list="list" :current="curNow" @change="sectionChange"></u-subsection>
		</u-sticky>
		<view class="clock-in-body">
			<!-- 打卡 -->
			<view v-if="curNow === 0" class="clock-in-and-out">
				<!-- 没有打卡规则 -->
				<view v-if="clockinRule === null">

				</view>
				<!-- 假期 -->
				<view v-else-if="isHoliday" class="holiday-body">
					<view class="holiday-content">
						<view style="width: 100%; height: 80%;">
							<image aspectFit class="holiday-img" src="../../static/clockIn/holiday.png"></image>
						</view>
						<view style="text-align: center;">
							<text class="holiday-text">
								今日休息
							</text>
						</view>
					</view>
				</view>
				<!-- 上班打卡 -->
				<view v-else>
					<view class="clock-in-heard">
						<view class="do-clock-in" @click="clockIn">
							<view class="clock-in-img">
								<view class="clockImsage" 
									:class="{'line-not': !isLine,'line-yes': isLine}">
									<view style="font-size: 30rpx;">
										<text>{{date}}</text>
									</view>
									<view>
										<text>{{time}}</text>
									</view>
								</view>
							</view>
							<view style="display: 1;margin-top: 20rpx;">
								<view v-if="isBusinessTrip || isWorkOutside" class="clock-text">
									<text>{{clockText}}</text>
								</view>
								<view v-if="positionShow" style="text-align: center;margin-top: 10rpx;">
									<text v-if="isPosition" style="color: #19be6b;">
										你已在打卡区域内
									</text>
									<text v-if="!isPosition" style="color: #ff9900;">
										当前不在打卡区域内
									</text>
								</view>
								<view class="position-text">
									<text>{{position}}</text>
								</view>
							</view>
						</view>
					</view>
					<view class="clock-records">
						<view class="clock-records-item">
							<view>
								<text>
									{{`上午：${attendance.clockinType == 0 ? clockinRule.forenoonCheckinTime +'——' + clockinRule.forenoonCheckoutTime : '不限打卡时间' }  `}}
								</text>
							</view>
							<view>
								<text>上班：{{clockTime(attendance.forenoonCheckinTime)}}</text>
								<text :style="{color:isFinColor}" 
									v-if="attendance.forenoonCheckinStatus !== 0">
									{{clockStatus(attendance.forenoonCheckinStatus,0)}}
								</text>
							</view>
							<view>
								<text>下班：{{clockTime(attendance.forenoonCheckoutTime)}}</text>
								<text :style="{color:isFoutColor}"
									v-if="attendance.forenoonCheckoutStatus !== 0">
									{{clockStatus(attendance.forenoonCheckoutStatus,1)}}
								</text>
							</view>
						</view>
						<view class="clock-records-item">
							<view>
								<text>
									{{`下午：${attendance.clockinType == 0 ? clockinRule.afternoonCheckinTime+'——'+clockinRule.afternoonCheckoutTime : '不限打卡时间'}`}}
								</text>
							</view>
							<view>
								<text>上班：{{clockTime(attendance.afternoonCheckinTime)}}</text>
								<text :style="{color:isAinColor}"
									v-if="attendance.afternoonCheckinStatus !== 0">
									{{clockStatus(attendance.afternoonCheckinStatus,2)}}
								</text>
							</view>
							<view>
								<text>下班：{{clockTime(attendance.afternoonCheckoutTime)}}</text>
								<text :style="{color:isAoutColor}"
									v-if="attendance.afternoonCheckoutStatus !== 0">
									{{clockStatus(attendance.afternoonCheckoutStatus,3)}}
								</text>
							</view>
						</view>
					</view>
					<!-- 提示弹窗 -->
					<u-modal :show="clockShow" title="提示" :content='clockContent' @confirm="clockShow = false"
						:closeOnClickOverlay="true" @close="clockShow = false">
					</u-modal>
				</view>
			</view>
			<!-- 申请 -->
			<view v-if="curNow === 1" class="apply-for">
				<!-- 没有打卡规则 -->
				<view v-if="clockinRule === null">

				</view>
				<!-- 申请 -->
				<view v-else class="apply-for-body">
					<view style="display: flex;">
						<view style="width: 200rpx; height: 250rpx;">
							<view class="apply-for-view" @click="toPage('/pages_clockIn/applyFor/AskForLeave')">
								<view class="apply-for-img-view">
									<image aspectFit class="apply-for-img" src="../../static/clockIn/AskForLeave.png">
									</image>
								</view>
							</view>
							<view style="text-align: center;">
								<text>
									请假
								</text>
							</view>
						</view>
						<view style="width: 200rpx; height: 250rpx;">
							<view class="apply-for-view" @click="toPage('/pages_clockIn/applyFor/signIn')">
								<view class="apply-for-img-view">
									<image aspectFit class="apply-for-img" src="../../static/clockIn/signIn.png"></image>
								</view>
							</view>
							<view style="text-align: center;">
								<text>
									补卡
								</text>
							</view>
						</view>
						<view style="width: 200rpx; height: 250rpx;">
							<view class="apply-for-view" @click="toPage('/pages_clockIn/applyFor/WorkOutside')">
								<view class="apply-for-img-view">
									<image aspectFit class="apply-for-img" src="../../static/clockIn/WorkOutside.png">
									</image>
								</view>
							</view>
							<view style="text-align: center;">
								<text>
									外勤
								</text>
							</view>
						</view>
						<view style="width: 200rpx; height: 250rpx;">
							<view class="apply-for-view" @click="toPage('/pages_clockIn/applyFor/businessTrip')">
								<view class="apply-for-img-view">
									<image aspectFit class="apply-for-img" src="../../static/clockIn/businessTrip.png">
									</image>
								</view>
							</view>
							<view style="text-align: center;">
								<text>
									出差
								</text>
							</view>
						</view>
					</view>
					<view style="margin-top: 10rpx;border-radius: 6px;">
						<u-cell-group>
							<u-cell title="申请记录" isLink url="/pages_clockIn/statistics/statistics">
							</u-cell>
						</u-cell-group>
					</view>
				</view>
			</view>
			<!-- 统计 -->
			<view v-if="curNow === 2" class="statistics">
				<!-- 没有打卡规则 -->
				<view v-if="clockinRule === null">

				</view>
				<view v-else>
					<!-- 展示 -->
					<view class="statistics-body-day" v-if="isDay">
						<view>
							<uni-calendar @change="change" @monthSwitch="monthSwitch"
								:selected="selected" />
						</view>
						<view>
							<u-cell-group>
								<u-cell title="打卡规则" isLink url="/pages_clockIn/statistics/ClockInRule">
								</u-cell>
							</u-cell-group>
						</view>
					</view>
				</view>
				<!-- 打卡详情弹窗 -->
				<u-popup mode="bottom" :round="10" :show="attendanceShow" 
					@close="attendanceShow = false" >
					<view style="width:100%;height: 650rpx;">
						<view class="statistics-attendance-title">
							<text>{{selectAttendance.clockingDate}}</text>
						</view>
						<view v-if="isAttendance" style="margin: 10rpx 0 20rpx 65rpx">
							<text>打卡类型：</text>
							<text>
								{{clockinType(selectAttendance.clockinType)}}
							</text>
						</view>
						<view v-if="isAttendance">
							<view class="clock-records-item">
								<view>
									<text>
										{{`上午：${clockinRule.forenoonCheckinTime}——${clockinRule.forenoonCheckoutTime}`}}
									</text>
								</view>
								<view>
									<text>上班：{{clockTime(selectAttendance.forenoonCheckinTime)}}</text>
									<text :style="{color:isFinColor}" 
										v-if="selectAttendance.forenoonCheckinStatus !== 0">
										{{clockStatus(selectAttendance.forenoonCheckinStatus,0)}}
									</text>
								</view>
								<view>
									<text>下班：{{clockTime(selectAttendance.forenoonCheckoutTime)}}</text>
									<text :style="{color:isFoutColor}"
										v-if="selectAttendance.forenoonCheckoutStatus !== 0">
										{{clockStatus(selectAttendance.forenoonCheckoutStatus,1)}}
									</text>
								</view>
							</view>
							<view class="clock-records-item">
								<view>
									<text>
										{{`下午：${clockinRule.afternoonCheckinTime}——${clockinRule.afternoonCheckoutTime}`}}
									</text>
								</view>
								<view>
									<text>上班：{{clockTime(selectAttendance.afternoonCheckinTime)}}</text>
									<text :style="{color:isAinColor}"
										v-if="selectAttendance.afternoonCheckinStatus !== 0">
										{{clockStatus(selectAttendance.afternoonCheckinStatus,2)}}
									</text>
								</view>
								<view>
									<text>下班：{{clockTime(selectAttendance.afternoonCheckoutTime)}}</text>
									<text :style="{color:isAoutColor}"
										v-if="selectAttendance.afternoonCheckoutStatus !== 0">
										{{clockStatus(selectAttendance.afternoonCheckoutStatus,3)}}
									</text>
								</view>
							</view>
						</view>
						<!-- 没有打卡记录 -->
						<view v-else style="text-align: center;">
							无打卡记录
						</view>
					</view>
				</u-popup>
			</view>
		</view>
	</view>
</template>

<script>
	import amap from '@/libs/amap-wx.130.js'
	import attendanceApi from '@/request/attendanceApi.js';
	import {
		setHMS
	} from '@/utils/timeUtil.js';

	var timer;
	export default {
		data() {
			return {
				nowTime: new Date("1997-01-01 00:00:00").getTime(),
				isLine: false,
				userInfo: {},
				isAttendance: false,
				attendanceShow: false,
				selectAttendance: {},
				isFinColor: '',
				isFoutColor: '',
				isAinColor: '',
				isAoutColor: '',
				clockSuccess: false,
				clockShow: false,
				clockContent: '',
				curNow: 0,
				list: ['打卡', '申请', '统计'],
				clockImg: '../../static/clockIn/waiting.png',
				clockText: '',
				clockStart: '',
				dayValue: '',
				monthValue: '',
				yearValue: '',
				yearMonthDay: null,
				yearMonth: null,
				year: null,
				clockinRule: null,
				holiday: null,
				isHoliday: false,
				date: '',
				time: '',
				attendance: {
					clockinRuleId: null,
					clockingDate: null,
					forenoonCheckinTime: null,
					forenoonCheckoutTime: null,
					afternoonCheckinTime: null,
					afternoonCheckoutTime: null,
					forenoonStatus: null,
					afternoonStatus: null,
					position: null,
					clockinType: 0,
				},
				attendanceList: [],
				fromData: {
					id: null,
					clockinRuleId: null,
					clockingDate: null,
					forenoonCheckinTime: null,
					forenoonCheckoutTime: null,
					afternoonCheckinTime: null,
					afternoonCheckoutTime: null,
					forenoonStatus: null,
					afternoonStatus: null,
					position: null,
				},
				isWorkOutside: false, // 外勤
				isBusinessTrip: false, // 出差
				point: [],
				polygon: [],
				position: '',
				isPosition: false,
				positionShow: false,
				isDay: true,
				isMonth: false,
				isYear: false,
				selected: [],
			}
		},
		onLoad() {
			this.userInfo = uni.getStorageSync("loginUser")
			this.getServerTime().then(data =>{
				this.nowTime = data;
				this.yearValue = new Date(this.nowTime).getFullYear()
				this.monthValue = new Date(this.nowTime).getMonth() + 1;
				this.dayValue = new Date(this.nowTime).getDate();
				timer = setInterval(() => {
					this.getNowTime()
				}, 1000)
			})
		},
		onShow() {
			this.getServerTime().then(data =>{
				this.nowTime = data;
			})
			this.getIsHoliday().then(res =>{
				if (!res){
					this.getClockinRule().then(data =>{
						if (data){
							this.getUserAttendance();
						}
					})
				}
			})
			// this.getCurrentLocation();
		},
		// 组件销毁时关闭定时器
		beforeDestroy() {
			clearInterval(timer)
		},
		methods: {
			// 返回上个页面
			toBack() {
				uni.navigateBack({
					delta: 1, // 返回的页面数，1表示返回上一页
					animationType: 'pop-out', // 页面关闭的动画效果
					animationDuration: 300, // 页面关闭的动画时间
				});
			},
			// 跳转页面
			toPage(url) {
				uni.navigateTo({
					url: url
				})
			},
			// 选项更改
			sectionChange(index) {
				this.curNow = index
				this.getClockinRule();
				if (index === 0) {
					this.getUserAttendance();
				} else if (index === 2) {
					const value = this.yearValue+"-"+this.addZero(this.monthValue)
					this.getSelected(value);
				}
			},
			// 获取服务器时间
			getServerTime(){
				return new Promise(resolve =>{
					attendanceApi.getServerTime().then(res =>{
						if (res.code == 200){
							let time = new Date(res.data).getTime();
							resolve(time);
						}
					})
				})
			},
			//获取当前时间
			getNowTime() {
				this.nowTime=this.nowTime+1000;
				var date = new Date(this.nowTime);
				//年 getFullYear()：四位数字返回年份
				var year = date.getFullYear(); //getFullYear()代替getYear()
				//月 getMonth()：0 ~ 11
				var month = date.getMonth() + 1;
				//日 getDate()：(1 ~ 31)
				var day = date.getDate();
				//时 getHours()：(0 ~ 23)
				var hour = date.getHours();
				//分 getMinutes()： (0 ~ 59)
				var minute = date.getMinutes();
				//秒 getSeconds()：(0 ~ 59)
				var second = date.getSeconds();
				var time = this.addZero(hour) + ":" + this.addZero(minute) + ':' + this.addZero(second);
				this.time = time;
				this.date = `${year}-${month}-${day}`
				// // 
				// if (hour < 12) {
				// 	this.clockText = "上午签到"
				// } else if (hour >= 12) {
				// 	this.clockText = "下午签到"
				// }
			},
			//小于10的拼接上0字符串
			addZero(s) {
				return s < 10 ? ('0' + s) : s;
			},
			// 获取当前位置
			getCurrentLocation() {
				var myAmapFun = new amap.AMapWX({
					key: 'e1ab59d6b27985a17484d293d47001d3' // 高德地图key
				});
				myAmapFun.getRegeo({
					success: (res) => {
						//成功回调
						//console.log("res=>",res[0])
						this.position = res[0].desc
						this.point = new Array;
						this.point.push(res[0].longitude)
						this.point.push(res[0].latitude)
						//console.log("经纬度=>",this.point);
						// 判断是否在打卡范围内
						this.isPosition = this.isPointInPolygon(this.point, this.clockinRule.coordinate);
					},
					fail: (info) => {
						//失败回调
						console.log('回调失败=>', info)
					}
				})
			},
			// 获取今天是否为节假日
			getIsHoliday() {
				return new Promise(resolve =>{
					attendanceApi.isHoliday().then(res => {
						if (res.code === 200) {
							this.isHoliday = parseFloat(res.data.isHoliday)
							// this.isHoliday = false;
							resolve(this.isHoliday);
						}
					})
				})
			},
			// 获取打卡规则
			getClockinRule() {
				return new Promise(resolve =>{
					attendanceApi.getClockinRule().then(res => {
						if (res.code === 200) {
							resolve(true);
						} else if (res.code === 204) {
							resolve(false);
							uni.showModal({
								title: '提示',
								content: res.message,
								showCancel: false,
								success: (res) => {
									if (res.confirm) {
										console.log('用户点击确定');
										uni.navigateBack({
											delta: 1
										})
									}
								}
							});
						}
					})
				})
			},
			// 获取个人打卡记录
			getUserAttendance() {
				attendanceApi.getUserAttendance().then(res => {
					if (res.code === 200) {
						if (res.data.attendanceVo.id != null){
							this.attendance = res.data.attendanceVo;
							this.clockinRule = res.data.clockinRuleVo;
							if (this.attendance.clockinType === 1) {
								this.isWorkOutside = true;
								this.clockText = '外勤打卡';
								this.positionShow = false;
							} else if (this.attendance.clockinType === 2) {
								this.isBusinessTrip = true;
								this.clockText = '出差打卡';
								this.positionShow = false;
							}else if (this.attendance.clockinType === 0){
								this.positionShow = true;
							}
							this.fromData.id = this.attendance.id
							this.fromData.clockinRuleId = this.attendance.clockinRuleId
							this.fromData.clockingDate = this.attendance.clockingDate
							// 获取当前位置
							this.getCurrentLocation();
						}else {
							let msg = "若是今天设置的打卡规则，则明天开始生效"
							uni.showModal({
								title: '打卡记录为空',
								content: msg,
								showCancel: false,
								success: (res) => {
									if (res.confirm) {
										console.log('用户点击确定');
										uni.navigateBack({
											delta: 1
										})
									}
								}
							});
						}
					}
				})
			},

			// 获取个人出勤记录列表
			getUserAttendanceList(){
				const data = {
					employeeId: this.userInfo.id,
					yearMonthDay: this.yearMonthDay,
					yearMonth: this.yearMonth,
					year: this.year,
					currentPage: 1,
					pageSize: 100,
				}
				attendanceApi.getUserAttendanceList(data).then(res =>{
					if (res.code === 200){
						this.attendanceList = res.data.attendanceList;
					}
				})
			},
			// 打卡判断
			clockIn() {
				// console.log("====>", this.attendance)
				// 判断打卡规则是否为空，为空提示设置打卡规则
				if (this.clockinRule == null) {
					uni.showToast({
						icon: "none",
						duration: 3000,
						title: "请联系管理员设置个人打卡规则"
					});
					return;
				}
				// 获取当前位置
				this.getCurrentLocation();
				// 打卡位置判断
				let flog = this.isPointInPolygon(this.point, this.clockinRule.coordinate);
				// 转化打卡时间段为毫秒
				const timePeriod = this.clockinRule.clockinTimePeriod * 60 * 1000;
				console.log("timePeriod===>",timePeriod)
				// 上午签到时间
				const FCheckinTimeList = String(this.clockinRule.forenoonCheckinTime).split(":");
				const FCheckinDate = setHMS(FCheckinTimeList[0], FCheckinTimeList[1], FCheckinTimeList[2]);
				const FCheckinTime = FCheckinDate.getTime();
				console.log("上午签到时间===>", FCheckinDate)
				// 上午签退时间
				const FCheckoutTimeList = String(this.clockinRule.forenoonCheckoutTime).split(":");
				const FCheckoutDate = setHMS(FCheckoutTimeList[0], FCheckoutTimeList[1], FCheckoutTimeList[2]);
				const FCheckoutTime = FCheckoutDate.getTime();
				console.log("上午签退时间===>", FCheckoutDate)
				// 下午签到时间
				const ACheckinTimeList = String(this.clockinRule.afternoonCheckinTime).split(":");
				const ACheckinDate = setHMS(ACheckinTimeList[0], ACheckinTimeList[1], ACheckinTimeList[2]);
				const ACheckinTime = ACheckinDate.getTime();
				console.log("下午签到时间===>", ACheckinDate)
				// 下午签退时间
				const ACheckoutTimeList = String(this.clockinRule.afternoonCheckoutTime).split(":");
				const ACheckoutDate = setHMS(ACheckoutTimeList[0], ACheckoutTimeList[1], ACheckoutTimeList[2]);
				const ACheckoutTime = ACheckoutDate.getTime();
				console.log("下午签退时间===>", ACheckoutDate)
				
				// 现在时间
				const today = new Date(this.nowTime);
				console.log("当前时间===>",today);
				console.log("nowTime===>",this.nowTime)
				if(this.attendance.clockinType != 0){
					this.fromData.clockinTypeCheckoutTime = today;
					this.fromData.position = this.point;
					this.submitData();
				}
				// 判断为上午还是下午打卡
				if (this.attendance.clockinType == 0 && this.nowTime < ACheckinTime && this.attendance.forenoonStatus !== 3 &&
						this.attendance.forenoonStatus !== 4 &&
						this.attendance.forenoonCheckoutTime === null){
					//当前时间小于规则下午签到时间，且上午状态不为旷工且不为请假，且上午签退时间为空
					console.log("========上午打卡========")
					if (this.nowTime < FCheckoutTime && this.attendance.forenoonStatus === null &&
						this.attendance.afternoonCheckinTime === null){
						// 当前时间小于规则上午签退时间，且上午状态为空，且上午签到为空
						console.log("========上午签到========")
						if (this.nowTime < (FCheckinTime-timePeriod)){
							// 当前时间小于规则上午签到时间-打卡时间段
							// 未到打卡时间
							this.clockContent = "未到打卡时间";
							this.clockShow = true;
						}else if(this.nowTime > (FCheckinTime-timePeriod) && 
							this.attendance.clockinType === 0 && !flog){
							// 当前时间大于规则上午签到时间-打卡时间段，打卡类型为普通，不在打卡范围内
							// 当前不在打卡区域内
							this.clockContent = "当前不在打卡区域内";
							this.clockShow = true;
						}else if(this.nowTime >= (FCheckinTime-timePeriod)){
							// 当前时间大于等于规则上午签到时间-打卡时间段
							// 正常打卡
							this.fromData.forenoonCheckinTime = today;
							this.fromData.position = this.point;
							this.submitData();
						}
					}else if(this.attendance.forenoonStatus !== null &&
						this.attendance.forenoonCheckoutTime === null){
						// 上午状态不为空，且上午签退为空
						console.log("========上午签退========")
						if (this.attendance.clockinType === 0 && !flog){
							// 打卡类型为普通，且不在打卡范围内
							// 当前不在打卡范围内
							this.clockContent = "当前不在打卡区域内";
							this.clockShow = true;
						}else if(this.nowTime < FCheckoutTime){
							// 当前时间小于规则上午签退时间
							// 提示未到签退时间，是否继续打卡
							let _this = this
							uni.showModal({
								title: '提示',
								content: '未到签退时间，确定要签退？',
								success: (res) => {
									if (res.confirm) {
										console.log('用户点击确定');
										_this.fromData.forenoonCheckoutTime = today;
										// 设置签到位置
										_this.fromData.position = _this.point;
										_this.submitData();
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							});
						}else if(this.nowTime >= FCheckoutTime){
							// 当前时间大于等于上午签退时间
							// 正常打卡
							this.fromData.forenoonCheckoutTime = today;
							this.fromData.position = this.point;
							this.submitData();
						}
					}
				}else if(this.attendance.clockinType == 0 && this.nowTime < FCheckoutTime && this.attendance.forenoonCheckoutTime != null){
					// 当前时间小于规则上午签退时间，且上午签退时间不为空
					this.clockContent = "已打上午卡";
					this.clockShow = true;
				}else if(this.attendance.clockinType == 0 && this.nowTime >= FCheckoutTime && this.nowTime < ACheckinTime &&
					(this.attendance.forenoonStatus == 3||this.attendance.forenoonStatus == 4)){
					// 当前时间大于等于规则上午签退时间，且小于规则下午签到时间，且上午状态为旷工或者请假
					console.log("========上午旷工或请假========")
					if(this.attendance.forenoonStatus === 3){
						// 上午状态为旷工
						// 请申请补卡
						this.clockContent = "请申请补卡";
						this.clockShow = true;
					}else {
						// 上午已请假
						this.clockContent = "上午已请假";
						this.clockShow = true;
					}
				}else if(this.attendance.clockinType == 0 && this.nowTime>=FCheckoutTime && this.attendance.afternoonStatus !== 3 &&
						this.attendance.afternoonStatus !== 4){
					// 当前时间大于等于规则上午签退时间，且下午状态不为旷工,且不为请假
					console.log("========下午打卡========")
					if (this.nowTime<ACheckoutTime && this.attendance.afternoonStatus === null &&
						this.attendance.afternoonCheckinTime === null){
						// 当前时间小于规则下午签退时间，且下午状态为空，且下午签到为空
						console.log("========下午签到========")
						if (this.nowTime < (ACheckinTime-timePeriod)){
							// 当前时间小于规则下午签到时间-打卡时间段
							// 未到打卡时间
							console.log("下午签到时间===>",ACheckinTime)
							console.log("ACheckinTime-timePeriod：",ACheckinTime-timePeriod)
							this.clockContent = "未到打卡时间";
							this.clockShow = true;
						}else if(this.nowTime >= (ACheckinTime-timePeriod) && 
							this.attendance.clockinType === 0 && !flog){
							// 当前时间大于等于规则下午签到时间-打卡时间段，打卡类型为普通，不在打卡范围内
							// 当前不在打卡范围内
							this.clockContent = "当前不在打卡区域内";
							this.clockShow = true;
						}else if(this.nowTime >= (ACheckinTime-timePeriod)){
							// 当前时间大于等于规则下午签到时间-打卡时间段
							// 正常打卡
							this.fromData.afternoonCheckinTime = today
							this.fromData.position = this.point;
							this.submitData();
						}
					}else if(this.attendance.afternoonStatus !== null && 
						this.attendance.afternoonCheckoutTime === null){
						// 下午状态不为空，且下午签退为空
						console.log("========下午签退========")
						if (this.attendance.clockinType === 0 && !flog){
							// 打卡类型为普通，且不在打卡范围内
							// 当前不在打卡范围内
							this.clockContent = "当前不在打卡区域内";
							this.clockShow = true;
						}else if(this.nowTime < ACheckoutTime){
							// 当前时间小于规则下午签退时间
							// 提示未到签退时间，是否继续打卡
							let _this = this
							uni.showModal({
								title: '提示',
								content: '未到签退时间，确定要签退？',
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
										_this.fromData.afternoonCheckoutTime = today
										// 设置签到位置
										_this.fromData.position = _this.point;
										_this.submitData();
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							});
						}else if(this.nowTime >= ACheckoutTime){
							// 当前时间大于等于下午签退时间
							// 打卡
							this.fromData.afternoonCheckoutTime = today
							this.fromData.position = this.point;
							this.submitData();
						}
					}else {
						this.clockContent = "今日已打卡";
						this.clockShow = true;
					}
				}else if(this.attendance.clockinType == 0 && this.nowTime >= FCheckoutTime && 
					(this.attendance.afternoonStatus === 3||
						this.attendance.afternoonStatus === 4)){
					// 当前时间大于等于规则上午签退时间，且下午状态为旷工或者请假
					console.log("========下午旷工或请假========")
					if(this.attendance.afternoonStatus === 3){
						// 下午状态为旷工
						// 请申请补卡
						this.clockContent = "请申请补卡";
						this.clockShow = true;
					}else {
						// 下午已请假
						this.clockContent = "下午已请假";
						this.clockShow = true;
					}
				}
			},
			// 重置数据
			reset() {
				this.fromData = {
					clockinRuleId: null,
					clockingDate: null,
					forenoonCheckinTime: null,
					forenoonCheckoutTime: null,
					afternoonCheckinTime: null,
					afternoonCheckoutTime: null,
					forenoonStatus: null,
					afternoonStatus: null,
					position: null,
				}
			},
			// 提交数据
			submitData() {
				console.log("提交的数据====>", this.fromData);
				let _this = this
				uni.showModal({
					title: '提示',
					content: '是否要打卡？',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
							console.log(_this.fromData)
							attendanceApi.updateAttendance(_this.fromData).then(res => {
								uni.showToast({
									title: '打卡成功',
									duration: 3000,
									icon: 'success'
								});
								if (res.code === 200) {
									_this.reset();
									_this.getUserAttendance();
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			// 判断点是否在多边形内
			isPointInPolygon(point, polygon) {
				//console.log("point=>", point)
				//console.log("polygon=>", polygon)
				var x = point[0],
					y = point[1];
				var inside = false;
				for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
					var xi = polygon[i][0],
						yi = polygon[i][1];
					var xj = polygon[j][0],
						yj = polygon[j][1];

					// 点的射线和多边形的一条边重合，并且点在边上
					if ((yi === yj && yi === y) && ((xi > x && xj < x) || (xi < x && xj > x))) {
						return true;
					}
					// 判断线段两端点是否在射线两侧
					if ((yi < y && yj >= y) || (yj < y && yi >= y)) {
						// 求射线和线段的交点x坐标，交点y坐标当然是y
						var intersect = xi + (y - yi) * (xj - xi) / (yj - yi);

						// 点在多边形的边上
						if (intersect === x) {
							return true;
						}
						// x大于点的x坐标，表示射线向右射出，如果穿过多边形边界，将 inside 取反
						if (intersect > x) {
							inside = !inside;
						}
					}
				}
				// 射线与多边形边界的交点数量为奇数时，点在多边形内部
				return inside;
			},
			// 打卡时间
			clockTime(time) {
				if (time !== null) {
					return time;
				}
				return "未打卡"
			},
			// 打卡状态
			clockStatus(status,index){
				let color = '';
				switch (status) {
					case 1:
						color = "#5ac725";
						if(index===0){
							this.isFinColor = color;
						}else if (index===1){
							this.isFoutColor = color;
						}else if (index===2){
							this.isAinColor = color;
						}else if (index===3){
							this.isAoutColor = color;
						}
						return "（正常）";
					case 2:
						color = "#f9ae3d";
						if(index===0){
							this.isFinColor = color;
						}else if (index===1){
							this.isFoutColor = color;
						}else if (index===2){
							this.isAinColor = color;
						}else if (index===3){
							this.isAoutColor = color;
						}
						if (index === 0 || index === 2){
							// 签到
							return "（迟到）";
						}else {
							// 签退
							return "（早退）";
						}
					case 3:
						color = "#f56c6c";
						if(index===0){
							this.isFinColor = color;
						}else if (index===1){
							this.isFoutColor = color;
						}else if (index===2){
							this.isAinColor = color;
						}else if (index===3){
							this.isAoutColor = color;
						}
						return "（旷工）";
					case 4:
						color = "#3c9cff";
						if(index===0){
							this.isFinColor = color;
						}else if (index===1){
							this.isFoutColor = color;
						}else if (index===2){
							this.isAinColor = color;
						}else if (index===3){
							this.isAoutColor = color;
						}
						return "（请假）";
					case 5:
						color = "#f9ae3d";
						if (index===1){
							this.isFoutColor = color;
						}else if (index===3){
							this.isAoutColor = color;
						}
						return "（未签退）";
				}
			},
			// 打卡类型
			clockinType(type){
				if (type === 1){
					return "外勤打卡"
				}else if(type === 2){
					return "出差打卡"
				}
				return "普通打卡"
			},
			// 统计，切换年月日
			selectDate(index) {
				if (index === 0) {
					this.isDay = true;
					this.isMonth = false;
					this.isYear = false;
				} else if (index === 1) {
					this.isDay = false;
					this.isMonth = true;
					this.isYear = false;
				} else {
					this.isDay = false;
					this.isMonth = false;
					this.isYear = true;
				}
			},
			// 获取指定日期的出勤记录
			change(e) {
				console.log("e===>", e)
				this.isAttendance = false;
				uni.showLoading({
					title: '加载中...',
					mask: true,
				});
				const data = {
					clockingDate: e.fulldate
				}
				attendanceApi.getUserAttendance(data).then(res =>{
					if (res.code === 200){
						this.selectAttendance = res.data.attendanceVo;
						if (this.selectAttendance.id != null){
							this.isAttendance = true;
						}
						this.selectAttendance.clockingDate = e.fulldate
						this.attendanceShow = true;
					}
				}).finally(() =>{
					uni.hideLoading();
				})
			},
			// 切换月份
			monthSwitch(e) {
				console.log("e===>", e)
				this.monthValue = e.month
				let value;
				if (typeof this.monthValue === 'number'){
					value = e.year+"-"+this.addZero(e.month);
				}else {
					value = e.year+"-"+e.month;
				}
				this.getSelected(value);
			},
			// 获取用户出勤列表
			getSelected(value){
				this.selected = []
				const data = {
					employeeId: this.userInfo.id,
					yearMonth: value,
					currentPage: 1,
					pageSize: 1000,
				}
				attendanceApi.getUserAttendanceList(data).then(res =>{
					if (res.code === 200){
						res.data.attendanceList.forEach(item =>{
							let info = ""
							if (item.forenoonStatus === 0 && item.afternoonStatus === 0){
								info = "正常"
							}else if (item.forenoonStatus === 4 || item.afternoonStatus === 4){
								info = "请假"
							}else if (item.forenoonStatus !== null || item.afternoonStatus !== null){
								info = "异常"
							}
							const data = {
								date: item.clockingDate,
								info: info
							}
							this.selected.push(data)
						})
					}
				})
			},
		}
	}
</script>

<style>
	.clock-in {
		min-height: 100vh;
		background-color: #eeeeef;
	}

	.clock-in-body {
		min-height: 82vh;
		background-color: #eeeeef;
	}

	.clock-in-and-out {
		height: 80vh;
		width: 95%;
		margin: auto;
		margin-top: 20rpx;
		background-color: #ffffff;
		border-radius: 6px;
		display: flex;
		flex-direction: column;
	}

	.clock-in-heard {
		width: 100%;
		height: 500rpx;
	}
	
	.position-text{
		text-align: center;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		margin-top: 10rpx;
	}
	
	.clock-text{
		text-align: center;
		margin-top: 10rpx;
		font-size: 35rpx;
		font-weight: bold;
		color: #5555ff;
	}

	.do-clock-in {
		width: 400rpx;
		height: 100%;
		margin: auto;
		display: flex;
		flex-direction: column;
	}

	.clock-in-img {
		width: 100%;
		height: 250rpx;
		margin-top: 40rpx;
		/* background-color: aqua; */
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.clockImsage {
		width: 250rpx;
		height: 250rpx;
		border-radius: 50%;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 45rpx;
		font-weight: 700;
	}
	
	.line-not{
		border: 18rpx solid #f9ae3d;
	}
	
	.line-yes{
		border: 18rpx solid #5ac725;
	}

	.clock-img {
		max-width: 100%;
		max-height: 100%;
		object-fit: cover;
	}

	.clock-records {
		flex: 1;
		width: 100%;
	}

	.clock-records-item {
		height: 200rpx;
		/* background-color: aqua; */
		line-height: 65rpx;
		margin-bottom: 30rpx;
		margin-left: 65rpx;
	}

	.holiday-body {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		/* 水平居中 */
		align-items: center;
		/* 垂直居中 */
	}

	.holiday-content {
		width: 350rpx;
		height: 400rpx;
		/* background-color: pink; */
	}

	.holiday-img {
		width: 100%;
		height: 100%;
	}

	.holiday-text {
		position: relative;
		bottom: 20px;
		font-size: 35rpx;
		color: #5677fc;
		font-weight: bold;
	}

	.apply-for {
		/* height: 30vh; */
		width: 95%;
		margin: auto;
		margin-top: 20rpx;
		background-color: #ffffff;
		border-radius: 6px;
	}

	.apply-for-body {
		
	}

	.apply-for-img {
		width: 100%;
		height: 100%;
	}

	.apply-for-view {
		width: 100%;
		height: 180rpx;
		border-radius: 15rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.apply-for-view:active {
		background-color: #f4f4f5;
	}

	.apply-for-img-view {
		width: 130rpx;
		height: 130rpx;
	}

	.statistics {
		height: 80vh;
		width: 95%;
		margin: auto;
		margin-top: 20rpx;
		/* background-color: #ffffff; */
		border-radius: 6px;
	}

	.statistics-body {}

	.statistics-body-title {
		width: 100%;
		height: 100rpx;
		display: flex;
		justify-content: space-between;
		background-color: #ffffff;
		border-radius: 6px 6px 0 0;
	}

	.statistics-body-time {
		width: 350rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.select-time-view {
		width: 300rpx;
		height: 70rpx;
		border-radius: 15rpx;
		background-color: #eeeeef;
		display: flex;
		align-items: center;
	}

	.statistics-body-date {
		width: 80rpx;
		height: 50rpx;
		text-align: center;
		margin-left: 15rpx;
		border-radius: 15rpx;
	}

	.select-time {
		background-color: #ffffff;
	}

	.statistics-body-day {
		background-color: #ffffff;
		border-radius: 0 0 6px 6px;
	}
	
	.statistics-attendance-title{
		width: 100%;
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
		font-size: 35rpx;
		font-weight: bold;
	}
</style>